package sg.com.techstudio.cfoconnect.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import sg.com.techstudio.cfoconnect.dao.EmailDao;
import sg.com.techstudio.cfoconnect.dao.RegisterDao;
import sg.com.techstudio.cfoconnect.obj.RegisterObj;

@Controller
public class PaypalController extends BaseController{
	private static final Log log = LogFactory.getLog(PaypalController.class);
	
	@Autowired
	private String paypal_server;
	
	@Autowired
	private RegisterDao registerDao;
	
	@Autowired
	private EmailDao emailDao;

	@Override
	protected String getModuleFolder() {
		return "paypal/";
	}
	
	@RequestMapping(value="pp"+SPRING_EXT)
	public String paypalIPN(Model model
			, HttpServletRequest req
			, @RequestParam(value="d", required=false) String department) throws UnsupportedEncodingException {
		log.debug("paypalIPN() entry");

		StringBuilder sb = new StringBuilder("cmd=_notify-validate");
		Enumeration<String> en = req.getParameterNames();
		while(en.hasMoreElements()){
			String paramName = en.nextElement();
			String paramValue = req.getParameter(paramName);
			log.info("add param ["+paramName+"] value=["+paramValue+"]");
			sb.append("&").append(paramName).append("=").append(URLEncoder.encode(paramValue, "UTF-8"));
		}
		
		try {
			log.debug("calling paypal url");
			URL u = new URL(paypal_server);
			URLConnection uc = u.openConnection();
			uc.setDoOutput(true);
			uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			PrintWriter pw = new PrintWriter(uc.getOutputStream());
			pw.println(sb.toString());
			pw.close();
			
			BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
			in.readLine();
			in.close();			
		} catch (Exception e) {
			log.error("exception when calling paypal:"+e.getMessage(), e);
		}
		
		try {
			String custom = req.getParameter("custom");
			String paymentStatus = req.getParameter("payment_status");
			String paymentAmount = req.getParameter("mc_gross");
			String payerEmail = req.getParameter("payer_email");
			
			if(!StringUtils.isEmpty(custom)) {
				log.info("~~~~~~~~~~Start Response from paypall~~~~~~~~~~~~");
				log.info("reg id: "+custom);
				log.info("paymentStatus : "+paymentStatus);
				log.info("payerEmail : "+payerEmail);
				log.info("paymentAmount : "+paymentAmount);
				log.info("~~~~~~~~~~End Response from paypall~~~~~~~~~~~~");
				
				RegisterObj r = registerDao.get(NumberUtils.toLong(custom));
				r.setPayerEmail(payerEmail);
				r.setPaymentStatus(StringUtils.equalsIgnoreCase("Completed", paymentStatus)?1:0);
				
				if(r.getPaymentStatus()==1) {
					registerDao.confirmAllStatus(r);
					registerDao.update(r);
					emailDao.sendEmail(r);
				}
			}
		} catch (Exception e) {
			log.error("exception updating local database:"+e.getMessage(), e);
		}
		
		return goToPageJsp("pp");
	}

}
